
// 初始化计数
let landlordWinCount = 0;
let landlordLossCount = 0;
let farmerWinCount = 0;
let farmerLossCount = 0;

// 初始化胜率记录数组
let landlordWinRateHistory = [];
let farmerWinRateHistory = [];
let totalWinRateHistory = [];

// 初始化 ECharts 实例
var pieDom = document.getElementById('pie');
var pieChart = echarts.init(pieDom);
var lineDom = document.getElementById('line');
var lineChart = echarts.init(lineDom);

// 初始化图表配置
var pieOption = {
    tooltip: {
        trigger: 'item'
    },
    legend: {
        top: '5%',
        left: 'center'
    },
    color: ['#3ba272', '#ee4455',  '#91cc75' ,'#ee6666'],
    series: [
        {
            name: '场数占比',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            padAngle: 5,
            itemStyle: {
                borderRadius: 10
            },
            emphasis: {
                label: {
                  show: true,
                  fontSize: 40,
                  fontWeight: 'bold'
                }
            },
            label: {
                show: true,
                position: 'outside'
            },
            labelLine: {
                show: true
            },
            data: [
                { value: 0, name: '龙队胜场' },
                { value: 0, name: '龙队败场' },
                { value: 0, name: '虎队胜场' },
                { value: 0, name: '虎队败场' }
            ]
        }
    ]
};

var lineOption = {
    tooltip: {
        trigger: 'axis'
    },
    legend: {
        data: ['龙队胜率', '虎队胜率', '总胜率']
    },
    xAxis: {
        type: 'category',
        data: [] // 横坐标为空数组，动态填充
    },
    yAxis: {
        type: 'value',
        axisLabel: {
            formatter: '{value}%'
        }
    },
    series: [
        {
            name: '龙队胜率',
            type: 'line',
            data: [] // 数据为空，动态填充
        },
        {
            name: '虎队胜率',
            type: 'line',
            data: [] // 数据为空，动态填充
        },
        {
            name: '总胜率',
            type: 'line',
            data: [] // 数据为空，动态填充
        }
    ]
};

// 设置初始图表
pieChart.setOption(pieOption);
lineChart.setOption(lineOption);
// 监听键盘事件
document.addEventListener('keydown', function(event) {
    // 增加操作
    if (event.key === 'z') {
        updateCount('landlord', 'win'); // 键盘z增加地主胜场
    } else if (event.key === 'x') {
        updateCount('landlord', 'loss'); // 键盘x增加地主败场
    } else if (event.key === 'c') {
        updateCount('farmer', 'win'); // 键盘c增加农民胜场
    } else if (event.key === 'v') {
        updateCount('farmer', 'loss'); // 键盘v增加农民败场
    }
    // 减少操作（反操作）
    else if (event.key === 'a') {
        updateCount('landlord', 'win', -1); // 键盘a减少地主胜场
    } else if (event.key === 's') {
        updateCount('landlord', 'loss', -1); // 键盘s减少地主败场
    } else if (event.key === 'd') {
        updateCount('farmer', 'win', -1); // 键盘d减少农民胜场
    } else if (event.key === 'f') {
        updateCount('farmer', 'loss', -1); // 键盘f减少农民败场
    }
});

// 更新计数并计算胜率（支持增加和减少）
function updateCount(type, result, change = 1) {
    // 更新地主或农民的胜场或败场
    if (type === 'landlord') {
        if (result === 'win') {
            if (change === -1 && landlordWinCount > 0) {
                landlordWinCount += change; // 减少地主胜场（确保不会变为负数）
            } else if (change === 1) {
                landlordWinCount += change; // 增加地主胜场
            }
        } else if (result === 'loss') {
            if (change === -1 && landlordLossCount > 0) {
                landlordLossCount += change; // 减少地主败场（确保不会变为负数）
            } else if (change === 1) {
                landlordLossCount += change; // 增加地主败场
            }
        }
    } else if (type === 'farmer') {
        if (result === 'win') {
            if (change === -1 && farmerWinCount > 0) {
                farmerWinCount += change; // 减少农民胜场（确保不会变为负数）
            } else if (change === 1) {
                farmerWinCount += change; // 增加农民胜场
            }
        } else if (result === 'loss') {
            if (change === -1 && farmerLossCount > 0) {
                farmerLossCount += change; // 减少农民败场（确保不会变为负数）
            } else if (change === 1) {
                farmerLossCount += change; // 增加农民败场
            }
        }
    }

    // 计算地主的总场数
    const landlordTotalGames = landlordWinCount + landlordLossCount;

    // 计算农民的总场数
    const farmerTotalGames = farmerWinCount + farmerLossCount;

    // 计算总场数（所有场次）
    const totalGames = landlordTotalGames + farmerTotalGames;

    // 计算地主胜率
    const landlordWinRate = landlordTotalGames > 0 ? (landlordWinCount / landlordTotalGames * 100).toFixed(2) : 0;

    // 计算农民胜率
    const farmerWinRate = farmerTotalGames > 0 ? (farmerWinCount / farmerTotalGames * 100).toFixed(2) : 0;

    // 计算总胜率
    const totalWinRate = totalGames > 0 ? ((landlordWinCount + farmerWinCount) / totalGames * 100).toFixed(2) : 0;

    // 保存当前胜率到数组
    landlordWinRateHistory.push(landlordWinRate);
    farmerWinRateHistory.push(farmerWinRate);
    totalWinRateHistory.push(totalWinRate);

    // 更新表格
    document.getElementById('landlordWinCount').textContent = landlordWinCount;
    document.getElementById('landlordLossCount').textContent = landlordLossCount;
    document.getElementById('farmerWinCount').textContent = farmerWinCount;
    document.getElementById('farmerLossCount').textContent = farmerLossCount;
    document.getElementById('landlordWinRate').textContent = landlordWinRate + '%';
    document.getElementById('farmerWinRate').textContent = farmerWinRate + '%';
    document.getElementById('totalWinRate').textContent = totalWinRate + '%';
    document.getElementById('totalGames').textContent = totalGames;

    // 调用更新 ECharts 饼图
    updatePieChart();
    // 调用更新 ECharts 折线图
    updateLineChart();

    // 调用颜色更新函数
    updateWinRateColors(landlordWinRate, farmerWinRate, totalWinRate);
    // 调用豆子面板更新
    updateAdditionalStats()
}

// 更新 ECharts 饼图
function updatePieChart() {
    // 更新图表数据
    pieChart.setOption({
        series: [{
            data: [
                { value: landlordWinCount, name: '龙队胜场' },
                { value: landlordLossCount, name: '龙队败场' },
                { value: farmerWinCount, name: '虎队胜场' },
                { value: farmerLossCount, name: '虎队败场' }
            ]
        }]
    });
}
// 更新 ECharts 折线图
function updateLineChart() {
    lineChart.setOption({
        xAxis: {
            data: Array.from({ length: landlordWinRateHistory.length }, (_, i) => i + 1) // 动态填充横坐标
        },
        series: [
            { data: landlordWinRateHistory },
            { data: farmerWinRateHistory },
            { data: totalWinRateHistory }
        ]
    });
}






    // 根据胜率更新背景色
function updateWinRateColors(landlordWinRate, farmerWinRate, totalWinRate) {
    // 胜率背景色设置
    const landlordRateCell = document.getElementById('landlordWinRate');
    const farmerRateCell = document.getElementById('farmerWinRate');
    const totalRateCell = document.getElementById('totalWinRate');

    // 更新地主胜率背景色
    landlordRateCell.style.backgroundColor = getBackgroundColor(landlordWinRate);

    // 更新农民胜率背景色
    farmerRateCell.style.backgroundColor = getBackgroundColor(farmerWinRate);

    // 更新总胜率背景色
    totalRateCell.style.backgroundColor = getBackgroundColor(totalWinRate);
}

// 根据胜率值返回背景色
function getBackgroundColor(winRate) {
    if (winRate <= 50) {
        return '#FFCCCC'; // 浅红色
    } else if (winRate <= 60) {
        return '#CCCCFF'; // 浅蓝色
    } else if (winRate <= 70) {
        return '#CCFFCC'; // 浅绿色
    } else {
        return 'gold'; // 金色
    }
}
// 更新净胜场、消耗豆子数和总分数
function updateAdditionalStats() {
    // 计算净胜场
    const netWinCount = (landlordWinCount + farmerWinCount) - (landlordLossCount + farmerLossCount);

    // 计算消耗豆子数
    const beanConsumption = 0;

    // 计算总分数
    const totalScore = netWinCount;

    // 更新表格中的字段值
    document.getElementById('netWinCount').textContent = netWinCount;
    document.getElementById('beanConsumption').textContent = beanConsumption;
    document.getElementById('totalScore').textContent = totalScore;
}
